//
//  DYTools.m
//  DellRow@iOS
//
//  Created by 吴欧 on 16/4/25.
//  Copyright © 2016年 吴欧. All rights reserved.
//

#import "DYTools.h"
#import <CommonCrypto/CommonDigest.h>
#import <SDImageCache.h>

@implementation DYTools
    
    //原始尺寸
    static CGRect oldframe;
    
    /**
     *  浏览大图
     *
     *  @param currentImageview 图片所在的imageView
     */
+(void)scanBigImageWithImageView:(UIImageView *)currentImageview{
    //当前imageview的图片
    UIImage *image = currentImageview.image;
    //当前视图
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    //背景
    UIView *backgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    //当前imageview的原始尺寸->将像素currentImageview.bounds由currentImageview.bounds所在视图转换到目标视图window中，返回在目标视图window中的像素值
    oldframe = [currentImageview convertRect:currentImageview.bounds toView:window];
    [backgroundView setBackgroundColor:[UIColor blackColor]];
    //此时视图不会显示
    [backgroundView setAlpha:0];
    //将所展示的imageView重新绘制在Window中
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:oldframe];
    [imageView setImage:image];
    [imageView setTag:0];
    [backgroundView addSubview:imageView];
    //将原始视图添加到背景视图中
    [window addSubview:backgroundView];
    
    
    //添加点击事件同样是类方法 -> 作用是再次点击回到初始大小
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideImageView:)];
    [backgroundView addGestureRecognizer:tapGestureRecognizer];
    
    //动画放大所展示的ImageView
    
    [UIView animateWithDuration:0.4 animations:^{
        CGFloat y,width,height;
        y = ([UIScreen mainScreen].bounds.size.height - image.size.height * [UIScreen mainScreen].bounds.size.width / image.size.width) * 0.5;
        //宽度为屏幕宽度
        width = [UIScreen mainScreen].bounds.size.width;
        //高度 根据图片宽高比设置
        height = image.size.height * [UIScreen mainScreen].bounds.size.width / image.size.width;
        [imageView setFrame:CGRectMake(0, y, width, height)];
        //重要！ 将视图显示出来
        [backgroundView setAlpha:1];
    } completion:^(BOOL finished) {
        
    }];
    
}
    
    /**
     *  恢复imageView原始尺寸
     *
     *  @param tap 点击事件
     */
+(void)hideImageView:(UITapGestureRecognizer *)tap{
    UIView *backgroundView = tap.view;
    //原始imageview
    UIImageView *imageView = [tap.view viewWithTag:0];
    //恢复
    [UIView animateWithDuration:0.4 animations:^{
        [imageView setFrame:oldframe];
        [backgroundView setAlpha:0];
    } completion:^(BOOL finished) {
        //完成后操作->将背景视图删掉
        [backgroundView removeFromSuperview];
    }];
}
    
#pragma mark - number转时间字符串
+ (NSString *)returndate:(NSNumber *)num withFormat:(NSString *)format{
    if ([self isBlankString:num.stringValue]||[num.stringValue isEqualToString:@"0"]) {
        return @"";
    }
    NSString *str1=[NSString stringWithFormat:@"%@",num];
    int x=[[str1 substringToIndex:10] intValue];
    NSDate *date1 = [NSDate dateWithTimeIntervalSince1970:x];
    NSDateFormatter *dateformatter=[[NSDateFormatter alloc]init];
    [dateformatter setDateFormat:format];
    NSString *str =  [dateformatter stringFromDate:date1];
    return str;
}
    
#pragma mark - 计算单个文件大小
+ (float)fileSizeAtPath:(NSString *)path
    {
        NSFileManager *fileManager=[NSFileManager defaultManager];
        if([fileManager fileExistsAtPath:path]){
            long long size=[fileManager attributesOfItemAtPath:path error:nil].fileSize;
            return size/1024.0/1024.0;
        }
        return 0;
    }
    
#pragma mark - 计算文件目录大小
+ (float)folderSizeAtPath:(NSString *)path
    {
        NSFileManager *fileManager=[NSFileManager defaultManager];
        float folderSize = 0.0;
        if ([fileManager fileExistsAtPath:path]) {
            NSArray *childerFiles=[fileManager subpathsAtPath:path];
            for (NSString *fileName in childerFiles) {
                NSString *absolutePath=[path stringByAppendingPathComponent:fileName];
                folderSize +=[DYTools fileSizeAtPath:absolutePath];
            }
            // SDWebImage框架自身计算缓存的实现
            folderSize += [[SDImageCache sharedImageCache] totalDiskSize]/1024.0/1024.0;
            return folderSize;
        }
        return 0;
    }
    
#pragma mark - 清理缓存
+ (void)clearCache:(NSString *)path
    {
        NSFileManager *fileManager=[NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:path]) {
            NSArray *childerFiles=[fileManager subpathsAtPath:path];
            for (NSString *fileName in childerFiles) {
                //如有需要，加入条件，过滤掉不想删除的文件
                NSString *absolutePath=[path stringByAppendingPathComponent:fileName];
                [fileManager removeItemAtPath:absolutePath error:nil];
            }
        }
        [[SDImageCache sharedImageCache] clearMemory];
    }

+ (NSString *) convertFileSize:(long long)size {
    long kb = 1024;
    long mb = kb * 1024;
    long gb = mb * 1024;
    
    if (size >= gb) {
        return [NSString stringWithFormat:@"%.1f GB", (float) size / gb];
    } else if (size >= mb) {
        float f = (float) size / mb;
        if (f > 100) {
            return [NSString stringWithFormat:@"%.0f MB", f];
        }else{
            return [NSString stringWithFormat:@"%.1f MB", f];
        }
    } else if (size >= kb) {
        float f = (float) size / kb;
        if (f > 100) {
            return [NSString stringWithFormat:@"%.0f KB", f];
        }else{
            return [NSString stringWithFormat:@"%.1f KB", f];
        }
    } else
        return [NSString stringWithFormat:@"%lld B", size];
}


+(NSString *)distanceWithStringMTransformKm:(CGFloat)distance {
    if (distance < 1000) {
       return [NSString stringWithFormat:@"%.0fm", distance];
   }else if (distance <= 100000) {
       float f = distance / 1000.0;
       return [NSString stringWithFormat:@"%.2fKm",f];
   }else{
       return [NSString stringWithFormat:@">100Km"];
   }
}
    
#pragma mark -  json转换
/// 返回字符串
+ (id)getObjectFromJsonString:(NSString *)jsonString
    {
        NSError *error = nil;
        if (jsonString) {
            id rev=[NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUnicodeStringEncoding] options:NSJSONReadingMutableLeaves error:&error];
            if (error==nil) {
                return rev;
            }
            else
            {
                return nil;
            }
        }
        return nil;
}

// 返回可变容器类字典 数组
+ (id)getContainersObjectFromJsonString:(NSString *)jsonString
    {
        NSError *error = nil;
        if (jsonString) {
            id rev=[NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&error];
            if (error==nil) {
                return rev;
            }
            else
            {
                return nil;
            }
        }
        return nil;
}
+ (NSArray *)stringToJSON:(NSString *)jsonStr {
    if (jsonStr) {
        id tmp = [NSJSONSerialization JSONObjectWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments | NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers error:nil];
        
        if (tmp) {
            if ([tmp isKindOfClass:[NSArray class]]) {
                
                return tmp;
                
            } else if([tmp isKindOfClass:[NSString class]]
                      || [tmp isKindOfClass:[NSDictionary class]]) {
                
                return [NSArray arrayWithObject:tmp];
                
            } else {
                return nil;
            }
        } else {
            return nil;
        }
        
    } else {
        return nil;
    }
}
    
+ (NSString *)getJsonStringFromObject:(id)object
    {
        if ([NSJSONSerialization isValidJSONObject:object])
        {
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object options:0 error:nil];
            return [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        }
        return nil;
    }
    
    //sha1是用来校验数据完整性的, 是哈希算法.
+ (NSString *)sha1:(NSString *)input
    {
        const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
        NSData *data = [NSData dataWithBytes:cstr length:input.length];
        
        uint8_t digest[CC_SHA1_DIGEST_LENGTH];
        CC_SHA1(data.bytes, (unsigned int)data.length, digest);
        NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
        
        for(int i=0; i<CC_SHA1_DIGEST_LENGTH; i++) {
            [output appendFormat:@"%02x", digest[i]];
        }
        return output;
    }
    
    // md5加密算法
+ (NSString *)md5:(NSString *)str
    {
        const char *cStr = [str UTF8String];
        unsigned char result[16];
        CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
        return [NSString stringWithFormat:
                @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                result[0], result[1], result[2], result[3],
                
                result[4], result[5], result[6], result[7],
                
                result[8], result[9], result[10], result[11],
                
                result[12], result[13], result[14], result[15]
                ];
    }
    
#pragma mark -  NSDate互转NSString
+ (NSDate *)NSStringToDate:(NSString *)dateString
    {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSDate *dateFromString = [[NSDate alloc] init];
        dateFromString = [dateFormatter dateFromString:dateString];
        return dateFromString;
    }
    
+ (NSDate *)NSStringToDate:(NSString *)dateString withFormat:(NSString *)formatestr{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:formatestr];
    NSDate *dateFromString = [[NSDate alloc] init];
    dateFromString = [dateFormatter dateFromString:dateString];
    return dateFromString;
}
    
+ (NSString *)NSDateToString:(NSDate *)dateFromString withFormat:(NSString *)formatestr
    {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:formatestr];
        NSString *strDate = [dateFormatter stringFromDate:dateFromString];
        return strDate;
    }
    
#pragma mark -  判断字符串是否为空,为空的话返回 “” （一般用于保存字典时）
/**用于保存字典时*/
+ (NSString *)IsNotNull:(id)string{
    NSString * str = (NSString*)string;
    if ([self isBlankString:str]){
        string = @"";
    }
    return string;
}

+ (NSString *)nullToDef:(NSString*)string {
    NSString * str = (NSString*)string;
    if ([self isBlankString:str]){
        string = @"-";
    }
    return string;
}

    
/**判断字符串是否为空字符的方法*/
+ (BOOL) isBlankString:(id)string {
    NSString * str = (NSString*)string;
    
    if (str == nil || str == NULL) {
        return YES;
    }
    if ([str isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([str isEqualToString:@"(null)"]) {
        return YES;
    }
    if (str.length==0) {
        return YES;
    }
    if ([[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return YES;
    }
    return NO;
}
    
    
#pragma mark - 使用subString去除float后面无效的0
+ (NSString *)changeFloatWithString:(NSString *)stringFloat
    
    {
        const char *floatChars = [stringFloat UTF8String];
        NSUInteger length = [stringFloat length];
        NSUInteger zeroLength = 0;
        NSInteger i = length-1;
        for(; i>=0; i--)
        {
            if(floatChars[i] == '0') {
                zeroLength++;
            } else {
                if(floatChars[i] == '.')
                i--;
                break;
            }
        }
        NSString *returnString;
        if(i == -1) {
            returnString = @"0";
        } else {
            returnString = [stringFloat substringToIndex:i+1];
        }
        return returnString;
    }
    
#pragma mark - 去除float后面无效的0
+ (NSString *)changeFloatWithFloat:(CGFloat)floatValue
    
    {
        return [self changeFloatWithString:[NSString stringWithFormat:@"%f",floatValue]];
    }
    
#pragma mark - 如何通过一个整型的变量来控制数值保留的小数点位数。以往我们通类似@"%.2f"来指定保留2位小数位，现在我想通过一个变量来控制保留的位数
+ (NSString *)newFloat:(float)value withNumber:(int)numberOfPlace
    {
        NSString *formatStr = @"%0.";
        formatStr = [formatStr stringByAppendingFormat:@"%df", numberOfPlace];
        NSLog(@"____%@",formatStr);
        
        formatStr = [NSString stringWithFormat:formatStr, value];
        NSLog(@"____%@",formatStr);
        
        printf("formatStr %s\n", [formatStr UTF8String]);
        return formatStr;
    }
    
#pragma mark -  阿里云压缩图片
+ (NSURL *)UrlWithStringForImage:(NSString*)string{
    NSString * str = [NSString stringWithFormat:@"%@@800w_600h_10Q.jpg",string];
    NSLog(@"加载图片地址=%@",str);
    return [NSURL URLWithString:str];
}
    
    //..去掉压缩属性“@800w_600h_10Q.jpg”
+ (NSString *)removeYaSuoAttribute:(NSString*)string{
    NSString * str = @"";
    if ([string rangeOfString:@"@"].location != NSNotFound) {
        NSArray * arry = [string componentsSeparatedByString:@"@"];
        str = arry[0];
    }
    return str;
}
    
#pragma mark - 字符串类型判断
    //..判断是否为整形：
+ (BOOL)isPureInt:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return[scan scanInt:&val] && [scan isAtEnd];
}
    
    //判断是否为浮点形：
+ (BOOL)isPureFloat:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    float val;
    return[scan scanFloat:&val] && [scan isAtEnd];
}
    
    
#pragma mark -  计算内容文本的高度方法
+ (CGFloat)HeightForText:(NSString *)text withSizeOfLabelFont:(CGFloat)font withWidthOfContent:(CGFloat)contentWidth
    {
        NSDictionary *dict = @{NSFontAttributeName:[UIFont systemFontOfSize:font]};
        CGSize size = CGSizeMake(contentWidth, 2000);
        CGRect frame = [text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil];
        return frame.size.height;
    }
    
#pragma mark -  计算字符串长度
+ (CGFloat)WidthForString:(NSString *)text withSizeOfFont:(UIFont *)font
    {
        NSDictionary *dict = @{NSFontAttributeName:font};
        CGSize size = [text sizeWithAttributes:dict];
        return size.width;
    }
    
    
    
#pragma mark -  计算两个时间相差多少秒
    
+ (NSInteger)getSecondsWithBeginDate:(NSString*)currentDateString  AndEndDate:(NSString*)tomDateString{
    
    NSDate * currentDate = [DYTools NSStringToDate:currentDateString withFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSInteger currSec = [currentDate timeIntervalSince1970];
    
    NSDate *tomDate = [DYTools NSStringToDate:tomDateString withFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSInteger tomSec = [tomDate timeIntervalSince1970];
    
    NSInteger newSec = tomSec - currSec;
    NSLog(@"相差秒：%ld",(long)newSec);
    return newSec;
}
    
    
#pragma mark - 根据出生日期获取年龄
+ (NSInteger)ageWithDateOfBirth:(NSDate *)date;
    {
        // 出生日期转换 年月日
        NSDateComponents *components1 = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:date];
        NSInteger brithDateYear  = [components1 year];
        NSInteger brithDateDay   = [components1 day];
        NSInteger brithDateMonth = [components1 month];
        
        // 获取系统当前 年月日
        NSDateComponents *components2 = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];
        NSInteger currentDateYear  = [components2 year];
        NSInteger currentDateDay   = [components2 day];
        NSInteger currentDateMonth = [components2 month];
        
        // 计算年龄
        NSInteger iAge = currentDateYear - brithDateYear - 1;
        if ((currentDateMonth > brithDateMonth) || (currentDateMonth == brithDateMonth && currentDateDay >= brithDateDay)) {
            iAge++;
        }
        
        return iAge;
    }
    
    
#pragma mark - 根据经纬度计算两个位置之间的距离
+ (double)distanceBetweenOrderBylat1:(double)lat1 lat2:(double)lat2 lng1:(double)lng1 lng2:(double)lng2{
    double dd = M_PI/180;
    double x1=lat1*dd,x2=lat2*dd;
    double y1=lng1*dd,y2=lng2*dd;
    double R = 6371004;
    double distance = (2*R*asin(sqrt(2-2*cos(x1)*cos(x2)*cos(y1-y2) - 2*sin(x1)*sin(x2))/2));
    //返回km
    return  distance/1000;
    
    //返回m
    //return   distance;
    
}


#pragma mark - 将某个时间戳转化成 时间
+ (NSString *)timestampSwitchTime:(NSString *)timestamp andFormatter:(NSString *)format {
    
    // 把时间戳转化成时间
    NSTimeInterval interval=[timestamp doubleValue] / 1000.0;
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
    NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [objDateformat setTimeZone:timeZone];
    [objDateformat setDateFormat:format];
    NSString * timeStr = [NSString stringWithFormat:@"%@",[objDateformat stringFromDate: date]];
    return timeStr;
}

#pragma mark - 将某个时间转化成 时间戳
+ (NSString *)timeSwitchTimestamp:(NSString *)formatTime andFormatter:(NSString *)format {
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    //例如你在国内发布信息,用户在国外的另一个时区,你想让用户看到正确的发布时间就得注意时区设置,时间的换算.
    //例如你发布的时间为2010-01-26 17:40:50,那么在英国爱尔兰那边用户看到的时间应该是多少呢?
    //他们与我们有7个小时的时差,所以他们那还没到这个时间呢...那就是把未来的事做了
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    //        NSString *nowtimeStr = [formatter stringFromDate:datenow];//----------将nsdate按formatter格式转成nsstring
    
    NSDate *dateNow2 = [formatter dateFromString:formatTime];
    
    //    时间转时间戳的方法:
    //    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];//这两个效果一样
    NSString *timeSp = [NSString stringWithFormat:@"%f", (double)[dateNow2 timeIntervalSince1970]* 1000.0];//这两个效果一样
    //    NSLog(@"timeSp:%@",timeSp); //时间戳的值
    
    return timeSp;
}

+ (void)callPhone:(NSString *)phone {
    if (@available(iOS 10.0, *)) {
        
        NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@", [phone qmui_trim]];
        UIApplication *application = [UIApplication sharedApplication];
        NSURL *URL = [NSURL URLWithString:str];
        [application openURL:URL options:@{} completionHandler:^(BOOL success) {
           //OpenSuccess=选择 呼叫 为 1  选择 取消 为0
//           NSLog(@"OpenSuccess=%d",success);

        }];
    } else {
        NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"telprompt://%@",[phone qmui_trim]];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
    }
}


+ (NSString *)uuid {
    CFUUIDRef uuid_ref = CFUUIDCreate(NULL);

    CFStringRef uuid_string_ref= CFUUIDCreateString(NULL, uuid_ref);

    NSString *uuid = [NSString stringWithString:(__bridge NSString *)uuid_string_ref];

    CFRelease(uuid_ref);

    CFRelease(uuid_string_ref);

    return [uuid lowercaseString];
}

+ (NSString *)createUuid {
    NSString *kRandomAlphabet = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    NSInteger kRandomLength = 32;
    NSMutableString *randomString = [NSMutableString stringWithCapacity:kRandomLength];
    for (int i = 0; i < kRandomLength; i++) {
        [randomString appendFormat: @"%C", [kRandomAlphabet characterAtIndex:arc4random_uniform((u_int32_t)[kRandomAlphabet length])]];
    }
    return randomString;
}

@end

